<template>
  <v-layout>
    <Header />
    <v-main>
      <v-container fluid>
        <!-- 轮播图/推广区 (可选) -->
        <v-row class="mb-6">
          <v-col cols="12">
            <v-card color="grey-lighten-3" flat>
              <v-card-text class="text-center py-16">
                <h1 class="text-primary text-h4 mb-2">欢迎来到我们的商城</h1>
                <p class="text-body-1">我们坚持为您提供最新、最好、最优质的商品</p>
                <v-btn color="primary" class="mt-4" size="large">网站公告</v-btn>
              </v-card-text>
            </v-card>
          </v-col>
        </v-row>

        <!-- 加载状态 -->
        <div v-if="loading" class="d-flex justify-center align-center py-12">
          <v-progress-circular
            indeterminate
            color="primary"
            size="64"
          ></v-progress-circular>
        </div>

        <!-- 错误提示 -->
        <v-alert
          v-if="error"
          type="error"
          variant="tonal"
          class="mb-6"
        >
          {{ error }}
        </v-alert>

        <!-- 商品分类和商品列表 -->
        <div v-if="!loading && categories.length === 0" class="text-center py-12">
          <v-icon size="64" color="grey-lighten-1">mdi-shopping-outline</v-icon>
          <p class="text-h6 mt-4 text-grey">暂无商品数据</p>
        </div>

        <div v-for="category in categories" :key="category.id" class="mb-8">
          <v-row>
            <v-col cols="12">
              <h2 class="text-h5 text-primary font-weight-bold mb-4">{{ category.name }}</h2>
              <v-divider class="mb-4"></v-divider>
            </v-col>
          </v-row>
          <v-row>
            <v-col
              v-for="product in category.products"
              :key="product.id"
              cols="12"
              sm="6"
              md="4"
              lg="3"
            >
              <ProductCard :product="product" />
            </v-col>
          </v-row>
        </div>
      </v-container>
    </v-main>
  </v-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Header from '~/components/Header.vue';
import ProductCard from '~/view/index/ProductCard.vue';

// 状态变量
const categories = ref([]);
const loading = ref(true);
const error = ref('');

// 获取商品分类和商品数据
const fetchCategories = async () => {
  try {
    loading.value = true;
    error.value = '';
    
    const response = await $fetch('/api/goods/categories');
    
    if (response.success) {
      categories.value = response.data || [];
    } else {
      error.value = response.message || '获取商品数据失败';
    }
  } catch (err) {
    console.error('获取商品分类错误:', err);
    error.value = '获取商品数据失败，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.product-card {
  transition: all 0.3s ease-in-out;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

/* 可以根据需要添加更多自定义样式 */
</style>